/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controller;

import controller.exceptions.NonexistentEntityException;
import controller.exceptions.RollbackFailureException;
import entidades.Cliente;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import entidades.Cardapio;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.transaction.UserTransaction;

/**
 *
 * @author Renato
 */
public class ClienteJpaController {
    @Resource
    private UserTransaction utx = null;
    @PersistenceUnit(unitName = "restaurantePU")
    private EntityManagerFactory emf = null;
    private Cliente cliente;
    private Integer id;
    private String nome;
    private String endRua;
    private String endBairro;
    private String endCidade;
    private String endCep;
    private String endUf;
    private String email;
    private Boolean receberNews;
    private List<Cardapio> cardapioCollection;
    private Integer idSelecionado;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public String novoCliente(){
        this.cliente = new Cliente();
        return "novoCliente";
    }

    public String listarCliente(){
        return "listarCliente";
    }

    public String excluirCliente() throws NonexistentEntityException, RollbackFailureException, Exception{
        cliente = findCliente(idSelecionado);
        destroy(idSelecionado);
        return "listarCliente";
    }

    public String editarCliente(){
        cliente = findCliente(idSelecionado);
        return "editarCliente";
    }

    public String create() throws RollbackFailureException, Exception {
        if (cliente.getCardapioCollection() == null) {
            cliente.setCardapioCollection(new ArrayList<Cardapio>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            em.getTransaction().begin();
            List<Cardapio> attachedCardapioCollection = new ArrayList<Cardapio>();
            for (Cardapio cardapioCollectionCardapioToAttach : cliente.getCardapioCollection()) {
                cardapioCollectionCardapioToAttach = em.getReference(cardapioCollectionCardapioToAttach.getClass(), cardapioCollectionCardapioToAttach.getId());
                attachedCardapioCollection.add(cardapioCollectionCardapioToAttach);
            }
            cliente.setCardapioCollection(attachedCardapioCollection);
            em.persist(cliente);
            for (Cardapio cardapioCollectionCardapio : cliente.getCardapioCollection()) {
                cardapioCollectionCardapio.getClienteCollection().add(cliente);
                cardapioCollectionCardapio = em.merge(cardapioCollectionCardapio);
            }
            utx.commit();
            em.getTransaction().commit();
            FacesMessage fm = new FacesMessage("Cliente '"+cliente.getNome()+"' inserido");
            FacesContext.getCurrentInstance().addMessage("Cliente inserido", fm);
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
        return "listarCliente";
    }

    public String edit() throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Cliente persistentCliente = em.find(Cliente.class, cliente.getId());
            List<Cardapio> cardapioCollectionOld = persistentCliente.getCardapioCollection();
            List<Cardapio> cardapioCollectionNew = cliente.getCardapioCollection();
            List<Cardapio> attachedCardapioCollectionNew = new ArrayList<Cardapio>();
            for (Cardapio cardapioCollectionNewCardapioToAttach : cardapioCollectionNew) {
                cardapioCollectionNewCardapioToAttach = em.getReference(cardapioCollectionNewCardapioToAttach.getClass(), cardapioCollectionNewCardapioToAttach.getId());
                attachedCardapioCollectionNew.add(cardapioCollectionNewCardapioToAttach);
            }
            cardapioCollectionNew = attachedCardapioCollectionNew;
            cliente.setCardapioCollection(cardapioCollectionNew);
            cliente = em.merge(cliente);
            for (Cardapio cardapioCollectionOldCardapio : cardapioCollectionOld) {
                if (!cardapioCollectionNew.contains(cardapioCollectionOldCardapio)) {
                    cardapioCollectionOldCardapio.getClienteCollection().remove(cliente);
                    cardapioCollectionOldCardapio = em.merge(cardapioCollectionOldCardapio);
                }
            }
            for (Cardapio cardapioCollectionNewCardapio : cardapioCollectionNew) {
                if (!cardapioCollectionOld.contains(cardapioCollectionNewCardapio)) {
                    cardapioCollectionNewCardapio.getClienteCollection().add(cliente);
                    cardapioCollectionNewCardapio = em.merge(cardapioCollectionNewCardapio);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = cliente.getId();
                if (findCliente(id) == null) {
                    throw new NonexistentEntityException("The cliente with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
        return "listarClientes";
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            em.getTransaction().begin();
            Cliente cliente;
            try {
                cliente = em.getReference(Cliente.class, id);
                cliente.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The cliente with id " + id + " no longer exists.", enfe);
            }
            List<Cardapio> cardapioCollection = cliente.getCardapioCollection();
            for (Cardapio cardapioCollectionCardapio : cardapioCollection) {
                cardapioCollectionCardapio.getClienteCollection().remove(cliente);
                cardapioCollectionCardapio = em.merge(cardapioCollectionCardapio);
            }
            em.remove(cliente);
            utx.commit();
            em.getTransaction().commit();
            FacesMessage fm = new FacesMessage("Cliente '"+cliente.getNome()+"' excluido");
            FacesContext.getCurrentInstance().addMessage("Cliente excluido", fm);
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

     public List<Cliente> getfindClienteEntities() {
        return findClienteEntities(true, -1, -1);
    }

    public List<Cliente> findClienteEntities() {
        return findClienteEntities(true, -1, -1);
    }

    public List<Cliente> findClienteEntities(int maxResults, int firstResult) {
        return findClienteEntities(false, maxResults, firstResult);
    }

    private List<Cliente> findClienteEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Cliente as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Cliente findCliente(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Cliente.class, id);
        } finally {
            em.close();
        }
    }

    public int getClienteCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Cliente as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

    public Cliente getCliente() {
        return cliente;
    }

    public void setCliente(Cliente cliente) {
        this.cliente = cliente;
    }

    public Integer getIdSelecionado() {
        return idSelecionado;
    }

    public void setIdSelecionado(Integer idSelecionado) {
        this.idSelecionado = idSelecionado;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getEndRua() {
        return endRua;
    }

    public void setEndRua(String endRua) {
        this.endRua = endRua;
    }

    public String getEndBairro() {
        return endBairro;
    }

    public void setEndBairro(String endBairro) {
        this.endBairro = endBairro;
    }

    public String getEndCidade() {
        return endCidade;
    }

    public void setEndCidade(String endCidade) {
        this.endCidade = endCidade;
    }

    public String getEndCep() {
        return endCep;
    }

    public void setEndCep(String endCep) {
        this.endCep = endCep;
    }

    public String getEndUf() {
        return endUf;
    }

    public void setEndUf(String endUf) {
        this.endUf = endUf;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Boolean getReceberNews() {
        return receberNews;
    }

    public void setReceberNews(Boolean receberNews) {
        this.receberNews = receberNews;
    }

    public List<Cardapio> getCardapioCollection() {
        return cardapioCollection;
    }

    public void setCardapioCollection(List<Cardapio> cardapioCollection) {
        this.cardapioCollection = cardapioCollection;
    }

}
